import React, {useState, useEffect, useMemo} from 'react';
import { show_mt, is_empty, obj_str, loc, PanelFind, Ret, Title, filter_row, useCmd, useHigh, GridTable } from 'sui';
import { load_col_psn } from 'task/psn/cmd';

const PsnView = ({ data, cur, hreturn, fix_col }) => {
    const [main, setMain] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        load_col_psn(setCol, fix_col);
    }, [fix_col]);

    useEffect(() => {
        const dw = obj_str(cur, "dw");

        const ret = [];

        data.forEach(d => {
            const tmp = d.batch;
            if (!tmp) {
                return;
            }

            d["dw"] = dw;

            ret.push(d);
        });

        setMain(ret);
    }, [data, cur, fix_col]);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        ];

        col.forEach(d => {
            if (d.sn.startsWith("box")) {
                return;
            }

            if (d.sn === "bsn") {
                return;
            }

            show_mt(tmp, d, 110);
        });

        return tmp;
    };

    const Right = () => (
        <div className="inline-flex">
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Title mod={obj_str(cur, "sn")} sub={loc("l_703")}/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow}/>
        </div>
    );
};

export {PsnView};
